<?php

namespace app\admin\controller;

use app\model\system\SystemAdmin;
use app\Request;
use think\db\exception\DataNotFoundException;
use think\db\exception\DbException;
use think\db\exception\ModelNotFoundException;
use think\response\Redirect;

/**
 * Class LoginController
 * @package app\admin\controller
 */
class LoginController extends SystemBasic
{
    /**
     * 登录展示页
     * Author: Albert3306
     * Date: 2020/11/13
     * @return string
     */
    public function index(): string
    {
        return $this->fetch('login/index');
    }

    /**
     * 登录
     * Author: Albert3306
     * Date: 2020/12/3
     * @param Request $request
     * @return mixed
     * @throws DataNotFoundException
     * @throws DbException
     * @throws ModelNotFoundException
     */
    public function login(Request $request)
    {
        // 检验验证码
        $data = $request->only(['username', 'password', 'captcha']);
        if (!captcha_check($data['captcha'])) return app('json')->fail('验证码值错误，请重新输入');

        // 检验账号密码
        if (SystemAdmin::login($data['username'], $data['password']))
            return app('json')->success('登录成功');
        return app('json')->fail(SystemAdmin::getErrorInfo('账号账号不存在'));
    }

    /**
     * 退出登录
     * Author: Albert3306
     * Date: 2020/12/4
     * @return Redirect
     */
    public function logout(): Redirect
    {
        SystemAdmin::clearLoginInfo();
        return redirect('/admin');
    }
}